package br.com.gscorp.bankLion.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import br.com.gscorp.bankLion.dto.ExceptionDTO;
import br.com.gscorp.bankLion.exception.BankLionException;

/**
 * @author marcos.fernandes
 *
 */
@Controller
@ControllerAdvice
public class ErroController {
	
	@ExceptionHandler(NullPointerException.class)
	@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ExceptionDTO nullPointerException(NullPointerException exception){
		ExceptionDTO erro = new ExceptionDTO(exception.getMessage(), exception.getStackTrace().toString());
		return erro;
	}
	
	@ExceptionHandler(BankLionException.class)
	@ResponseBody
	public ExceptionDTO errorHandler(BankLionException exception, HttpServletResponse response) {
		response.setStatus(exception.getStatusCode());
		ExceptionDTO erro = new ExceptionDTO(exception.getMessage(), exception.getStackTrace().toString());
		return erro;
	}
	
	@ExceptionHandler(JpaSystemException.class)
	@ResponseBody
	public ExceptionDTO errorHandler(JpaSystemException exception, HttpServletResponse response) {
		response.setStatus(412);
		ExceptionDTO erro = new ExceptionDTO(exception.getMessage(), exception.getStackTrace().toString());
		return erro;
	}
}
